import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useTranslation } from 'react-i18next';
import {
  Container,
  Typography,
  Box,
  Paper,
  Button,
  FormControl,
  FormLabel,
  FormControlLabel,
  RadioGroup,
  Radio,
  Switch,
  Divider,
  Grid,
  LinearProgress
} from '@mui/material';
import { RootState } from '../redux/store';
import { updatePreferences } from '../redux/slices/authSlice';
import { setTheme } from '../redux/slices/uiSlice';
import { addAlert } from '../redux/slices/uiSlice';

const Settings: React.FC = () => {
  const dispatch = useDispatch();
  const { user, loading } = useSelector((state: RootState) => state.auth);
  const { theme } = useSelector((state: RootState) => state.ui);
  const { t } = useTranslation();
  
  const [formData, setFormData] = useState({
    theme: theme,
    aiProvider: user?.preferences?.aiProvider || 'ChatGPT',
    notifications: {
      email: user?.preferences?.notifications?.email || false,
      push: user?.preferences?.notifications?.push || false
    }
  });
  
  const handleThemeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newTheme = e.target.value as 'light' | 'dark';
    setFormData({
      ...formData,
      theme: newTheme
    });
    dispatch(setTheme(newTheme));
  };
  
  const handleAIProviderChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData({
      ...formData,
      aiProvider: e.target.value
    });
  };
  
  const handleNotificationChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData({
      ...formData,
      notifications: {
        ...formData.notifications,
        [e.target.name]: e.target.checked
      }
    });
  };
  
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    try {
      await dispatch(updatePreferences(formData) as any);
      dispatch(addAlert({
        type: 'success',
        message: t('settings.success.updated')
      }));
    } catch (error) {
      dispatch(addAlert({
        type: 'error',
        message: t('settings.errors.updateFailed')
      }));
    }
  };
  
  if (loading || !user) {
    return <LinearProgress />;
  }
  
  return (
    <Container maxWidth="md" sx={{ mt: 4 }}>
      <Typography variant="h4" gutterBottom>
        {t('settings.title')}
      </Typography>
      
      <Paper sx={{ p: 3 }}>
        <form onSubmit={handleSubmit}>
          <Grid container spacing={4}>
            <Grid item xs={12}>
              <FormControl component="fieldset">
                <FormLabel component="legend">{t('settings.theme')}</FormLabel>
                <RadioGroup
                  row
                  name="theme"
                  value={formData.theme}
                  onChange={handleThemeChange}
                >
                  <FormControlLabel
                    value="light"
                    control={<Radio />}
                    label={t('settings.light')}
                  />
                  <FormControlLabel
                    value="dark"
                    control={<Radio />}
                    label={t('settings.dark')}
                  />
                </RadioGroup>
              </FormControl>
            </Grid>
            
            <Grid item xs={12}>
              <Divider />
            </Grid>
            
            <Grid item xs={12}>
              <FormControl component="fieldset">
                <FormLabel component="legend">{t('settings.aiProvider')}</FormLabel>
                <RadioGroup
                  row
                  name="aiProvider"
                  value={formData.aiProvider}
                  onChange={handleAIProviderChange}
                >
                  <FormControlLabel
                    value="ChatGPT"
                    control={<Radio />}
                    label="ChatGPT"
                  />
                  <FormControlLabel
                    value="Claude"
                    control={<Radio />}
                    label="Claude"
                  />
                  <FormControlLabel
                    value="DeepSeek"
                    control={<Radio />}
                    label="DeepSeek"
                  />
                </RadioGroup>
              </FormControl>
            </Grid>
            
            <Grid item xs={12}>
              <Divider />
            </Grid>
            
            <Grid item xs={12}>
              <FormControl component="fieldset">
                <FormLabel component="legend">{t('settings.notifications')}</FormLabel>
                <Box mt={1}>
                  <FormControlLabel
                    control={
                      <Switch
                        checked={formData.notifications.email}
                        onChange={handleNotificationChange}
                        name="email"
                        color="primary"
                      />
                    }
                    label={t('settings.emailNotifications')}
                  />
                </Box>
                <Box>
                  <FormControlLabel
                    control={
                      <Switch
                        checked={formData.notifications.push}
                        onChange={handleNotificationChange}
                        name="push"
                        color="primary"
                      />
                    }
                    label={t('settings.pushNotifications')}
                  />
                </Box>
              </FormControl>
            </Grid>
            
            <Grid item xs={12}>
              <Button
                type="submit"
                variant="contained"
                color="primary"
                sx={{ mt: 2 }}
              >
                {t('settings.saveSettings')}
              </Button>
            </Grid>
          </Grid>
        </form>
      </Paper>
    </Container>
  );
};

export default Settings; 